'use strict';

const Service = require('egg').Service;

class LoginService extends Service {
    // 登录
    async login() {
        let e = this.ctx.request.body.user;
        let userInfo = await this.app.model.User.findAll({ where: { username: e.username } });
        let msg;
        let code;
        let token;
        // let res;
        let a = userInfo.find((item) => {
            return e.username === item.username && e.password === item.password;
        });
        if (a) {
            code = 200
            msg = "登陆成功";
            token = this.app.jwt.sign(e, this.app.config.jwt.secret)
            // res = await this.app.model.User.findAll()

        } else {
            code = 400
            msg = "登录失败"
        }
        // 返回密码 极不友好 将密码设置 undefind
        userInfo[0].dataValues.password = undefined
        return {
            code,
            msg,
            token,
            userInfo
        }
    }
    // 修改密码
    async editpassword() {
        let e = this.ctx.request.body.user;
        console.log(e)
        let userInfo = await this.app.model.User.findAll();
        let msg;
        let code;
        let a = userInfo.find((item) => {
            return e.username === item.username && e.oldPassword === item.password;
        });
        if (a) {
            await this.app.model.User.update({ password: e.newPassword }, {
                where: {
                    username: e.username
                }
            })
            code = 200
            msg = "修改密码成功";
        } else {
            code = 400
            msg = "旧密码错误"
        }
        return {
            code,
            msg
        }
    }
}

module.exports = LoginService;
